package com.bailian.common.core.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.TypeReference;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * MyBatis JSON列表类型处理器
 * 用于处理数据库JSON字段与Java List之间的转换
 * 
 * @author bailian
 * @date 2025-08-08
 */
@MappedTypes(List.class)
public class JsonListTypeHandler extends BaseTypeHandler<List<?>> {

    private final TypeReference<List<Object>> typeReference = new TypeReference<List<Object>>() {};

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<?> parameter, JdbcType jdbcType) throws SQLException {
        if (parameter != null) {
            ps.setString(i, JSON.toJSONString(parameter));
        } else {
            ps.setNull(i, jdbcType.TYPE_CODE);
        }
    }

    @Override
    public List<?> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return parseJsonList(value);
    }

    @Override
    public List<?> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return parseJsonList(value);
    }

    @Override
    public List<?> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return parseJsonList(value);
    }

    /**
     * 解析JSON字符串为List
     * 
     * @param value 数据库中的值
     * @return 解析后的List
     */
    private List<?> parseJsonList(String value) {
        if (value == null || value.trim().isEmpty()) {
            return null;
        }
        
        try {
            return JSON.parseObject(value, typeReference);
        } catch (JSONException e) {
            // 如果解析失败，返回null
            return null;
        }
    }
} 